package com.collect.zambia.zhiScene.zhiWidget.zhiSubmitRecTagView;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Context;
import android.graphics.drawable.ColorDrawable;
import android.os.IBinder;
import androidx.fragment.app.FragmentManager;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.listener.OnTimeSelectListener;
import com.bigkoo.pickerview.view.TimePickerView;
import com.collect.zambia.R;
import com.collect.zambia.zhiBean.zhiSend.ZHISCaseRecordEntity;
import com.collect.zambia.MyApplication;
import com.collect.zambia.zhiHelper.ZHIDsHelper;
import com.collect.zambia.zhiScene.zhiWidget.zhiDialog.ZHIDialogMessage;
import com.collect.zambia.zhiScene.zhiWidget.zhiOptionView.ZHIOption;
import com.collect.zambia.zhiScene.zhiWidget.zhiOptionView.ZHIOptionView;
import com.collect.zambia.zhiScene.zhiWidget.zhiStepView.ZHINextStepView;
import com.collect.zambia.zhiUtils.StringUtil;
import com.collect.zambia.zhiUtils.ToastUtil;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;

public class ZHISubmitRecTagView extends PopupWindow {

    private View mMenuView;
    private LinearLayout ll_pop_layout;
    private TextView tv_name;
    private TextView tv_contact;
    private TextView tv_call_result;
    private ImageView iv_select_call_result;
    private TextView tv_promised_due_time_des;
    private LinearLayout ll_promised_due_time;
    private TextView tv_promised_due_time;
    private ImageView iv_select_promised_due_time;

    private EditText et_remarks;
    private ZHINextStepView btn_negtive;

    private OnSubmitRecTagItemClickListener mOnSubmitRecTagItemClickListener;
    private Context mContext;
    private FragmentManager mFragmentManager;
    private View mParentView;
    private ZHIOptionView mZHIOptionView;
    private TimePickerView mPromisedDueTimePickerView;
    private String mContactRelation;
    private String mPhone;

    @SuppressLint("ClickableViewAccessibility,CutPasteId")
    public ZHISubmitRecTagView(Context context) {
        super(context);
        mContext = context;

        LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        mMenuView = inflater.inflate(R.layout.popview_record_tag, null);
        ll_pop_layout = mMenuView.findViewById(R.id.ll_pop_layout);
        tv_name = mMenuView.findViewById(R.id.tv_name);
        tv_contact = mMenuView.findViewById(R.id.tv_contact);
        tv_call_result = mMenuView.findViewById(R.id.tv_call_result);
        iv_select_call_result = mMenuView.findViewById(R.id.iv_select_call_result);
        tv_promised_due_time = mMenuView.findViewById(R.id.tv_promised_due_time);
        ll_promised_due_time = mMenuView.findViewById(R.id.ll_promised_due_time);
        tv_promised_due_time_des = mMenuView.findViewById(R.id.tv_promised_due_time_des);
        iv_select_promised_due_time = mMenuView.findViewById(R.id.iv_select_promised_due_time);

        et_remarks = mMenuView.findViewById(R.id.et_remarks);
        btn_negtive = mMenuView.findViewById(R.id.btn_negtive);
        mZHIOptionView = new ZHIOptionView(mContext);

        //设置SelectPicPopupWindow的View
        this.setContentView(mMenuView);
        //设置SelectPicPopupWindow弹出窗体的宽
        this.setWidth(ViewGroup.LayoutParams.MATCH_PARENT);
        //设置SelectPicPopupWindow弹出窗体的高
        this.setHeight(ViewGroup.LayoutParams.MATCH_PARENT);
        //设置SelectPicPopupWindow弹出窗体可点击
        this.setFocusable(true);
        //设置SelectPicPopupWindow弹出窗体动画效果
        this.setAnimationStyle(R.style.PopWindowFromBottom);
        //实例化一个ColorDrawable颜色为半透明
        ColorDrawable dw = new ColorDrawable(0xa0000000);
        //设置SelectPicPopupWindow弹出窗体的背景
        this.setBackgroundDrawable(dw);
        this.setClippingEnabled(false);

        mPromisedDueTimePickerView = showPromisedDueDatePicker(mContext);

        ll_pop_layout.setOnClickListener(v -> dismissKeyboard(ll_pop_layout));
        iv_select_call_result.setOnClickListener(v -> showOption(""));
        tv_call_result.setOnClickListener(v -> showOption(""));
        tv_promised_due_time.setOnClickListener(v -> mPromisedDueTimePickerView.show());
        iv_select_promised_due_time.setOnClickListener(v -> mPromisedDueTimePickerView.show());

        btn_negtive.setOnMenuItemDidChangedListener(item -> {
            String remarkContent = et_remarks.getText().toString().trim();
            if (remarkContent.isEmpty()) {
                ToastUtil.s("Please enter the content of the note.");
                return;
            }
            boolean hadCall = checkCallResult(mPhone);
            if (!hadCall) return;

            if (mOnSubmitRecTagItemClickListener != null) {
                mOnSubmitRecTagItemClickListener.onSubmitClick();
            }
        });

        mZHIOptionView.setOptionClickListener((type, result) -> {
            try {
                result = StringUtil.safeString(result);
                tv_call_result.setText(result);
                tv_call_result.setTextColor(mContext.getResources().getColor(R.color.theme_black_0));

                //显示承诺还款时间段
                tv_promised_due_time_des.setVisibility(result.equalsIgnoreCase(mContext.getResources().getString(R.string.call_result_ptp)) ? View.VISIBLE : View.GONE);
                ll_promised_due_time.setVisibility(result.equalsIgnoreCase(mContext.getResources().getString(R.string.call_result_ptp)) ? View.VISIBLE : View.GONE);
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
        mMenuView.setOnTouchListener((v, event) -> {
            int height = mMenuView.findViewById(R.id.ll_pop_layout).getTop();
            int y = (int) event.getY();
            if (event.getAction() == MotionEvent.ACTION_UP) {
                if (y < height) {
                    dismiss();
                }
            }
            return true;
        });
    }

    public void showOption(String type) {
        try {
            dismissKeyboard(ll_pop_layout);
            if (mZHIOptionView == null) {
                mZHIOptionView = new ZHIOptionView(mContext);
            }
            ArrayList<ZHIOption> arrayList = new ArrayList<>();
            String[] results = {
                    mContext.getResources().getString(R.string.call_result_ptp),
                    mContext.getResources().getString(R.string.call_result_rnr),
                    mContext.getResources().getString(R.string.call_result_fake),
                    mContext.getResources().getString(R.string.call_result_out_of_coverage),
                    mContext.getResources().getString(R.string.call_result_switched_off),
                    mContext.getResources().getString(R.string.call_result_innvalid_num),
                    mContext.getResources().getString(R.string.call_result_msg_sent),
                    mContext.getResources().getString(R.string.call_result_paid),
                    mContext.getResources().getString(R.string.call_result_connected)
            };
            for (int i = 0; i < results.length; i++) {
                ZHIOption option = new ZHIOption();
                option.setTitle(results[i]);
                arrayList.add(option);
            }
            String title = "Select Call Result";
            mZHIOptionView.setOptionTitle(title);
            mZHIOptionView.setOptionType(type);
            mZHIOptionView.setNewData(arrayList);
            mZHIOptionView.showAtLocation(mParentView, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void setFragmentManager(FragmentManager fragmentManager) {
        mFragmentManager = fragmentManager;
    }

    public void setmParentView(View parentView) {
        mParentView = parentView;
    }

    public void setName(String name) {
        try {
            tv_name.setText(name);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void setContact(String contact) {
        try {
            mPhone = contact;
            String EncryptFormatter = StringUtil.phoneNumberEncryptFormatter(contact);
            tv_contact.setText(EncryptFormatter);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void setContactRelation(String contactRelation) {
        this.mContactRelation = contactRelation;
    }

    public void setCallResult(String result) {
        if (TextUtils.isEmpty(result)) {
            return;
        }
        try {
            tv_call_result.setText(result);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void fillRecTagParamsV2(ZHISCaseRecordEntity zhiSCaseRecordEntity) {
        try {
            if (zhiSCaseRecordEntity == null) {
                zhiSCaseRecordEntity = new ZHISCaseRecordEntity();
            }
            String callresult = tv_call_result.getText().toString().trim();
            callresult = callresult.startsWith("--") ? "" : callresult;
            zhiSCaseRecordEntity.setContactMobile(StringUtil.safeString(mPhone));
            zhiSCaseRecordEntity.setContactName(tv_name.getText().toString().trim());
            zhiSCaseRecordEntity.setContactResult(callresult);
            zhiSCaseRecordEntity.setContactRelation(mContactRelation);
            zhiSCaseRecordEntity.setRemark(et_remarks.getText().toString().trim());

            String ptpTime = tv_promised_due_time.getText().toString().trim();
            ptpTime = ptpTime.startsWith("--") ? "" : ptpTime;
            zhiSCaseRecordEntity.setPtpTime(ptpTime);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void setSubmitRecTagItemClickListener(OnSubmitRecTagItemClickListener submitRecTagItemClickListener) {
        this.mOnSubmitRecTagItemClickListener = submitRecTagItemClickListener;
    }

    public interface OnSubmitRecTagItemClickListener {
        void onSubmitClick();
    }

    @SuppressLint("SimpleDateFormat,SetTextI18n")
    private TimePickerView showPromisedDueDatePicker(Context context) {
        OnTimeSelectListener mOnTimeSelectListener = (date, v) -> {
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm");
            String dateString = format.format(date);
            tv_promised_due_time.setText(dateString);
            tv_promised_due_time.setTextColor(mContext.getResources().getColor(R.color.theme_black_0));
        };

        Calendar startCalendar = Calendar.getInstance();
        startCalendar.set(2021, 1, 15);
        Calendar endCalendar = Calendar.getInstance();
        endCalendar.set(2030, 9, 15);
        TimePickerView pvTime = new TimePickerBuilder(context, mOnTimeSelectListener)
                .setType(new boolean[]{true, true, true, true, true, false})
                .setCancelText(" ")
                .setContentTextSize(18)
                .setTitleSize(20)
                .setTitleText("")
                .setTitleBgColor(context.getResources().getColor(R.color.theme_blue_4))
                .setTextColorCenter(context.getResources().getColor(R.color.theme_black_0))
                .setOutSideCancelable(true)
                .setRangDate(startCalendar, endCalendar)
                .setTitleColor(context.getResources().getColor(R.color.theme_black_0))
                .setCancelColor(context.getResources().getColor(R.color.white))
                .setSubmitColor(context.getResources().getColor(R.color.white))
                .isDialog(true)
                .build();

        Dialog mDialog = pvTime.getDialog();
        if (mDialog != null) {
            FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(
                    ViewGroup.LayoutParams.MATCH_PARENT,
                    ViewGroup.LayoutParams.WRAP_CONTENT,
                    Gravity.BOTTOM);

            params.leftMargin = 0;
            params.rightMargin = 0;
            pvTime.getDialogContainerLayout().setLayoutParams(params);

            Window dialogWindow = mDialog.getWindow();
            if (dialogWindow != null) {
                dialogWindow.setWindowAnimations(com.bigkoo.pickerview.R.style.picker_view_slide_anim);
                dialogWindow.setGravity(Gravity.BOTTOM);
                dialogWindow.setDimAmount(0.3f);
            }
        }

        return pvTime;
    }

    private void dismissKeyboard(View view) {
        try {
            // 隐藏键盘
            IBinder token = view.getWindowToken();
            InputMethodManager inputMethodManager = (InputMethodManager) MyApplication.getAppContext().getSystemService(Context.INPUT_METHOD_SERVICE);
            inputMethodManager.hideSoftInputFromWindow(token,
                    InputMethodManager.HIDE_NOT_ALWAYS);
        } catch (Exception e){
            e.printStackTrace();
        }
    }

    private boolean checkCallResult(String mobile) {
        int result = ZHIDsHelper.getInstance().checkCallRecord(mobile);
        if (ZHIDsHelper.RESULT_CALL_SUCCESS == result) {
            return true;
        }

        if (ZHIDsHelper.RESULT_CALL_DURATION_IS_ZERO == result) {
            return true;
        }

        ZHIDialogMessage.showDialog(mContext,
                mContext.getResources().getString(R.string.prompt),
                "You are cheating now, the behavior has been recorded, please work carefully-" + result,
                true,
                tag -> {
                });

        return false;
    }

}
